// pages/doQuestion/doQuestion.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ishidden: true,
    allQuestion: [],
    allQuestionConstantLenght: "",
    currentAllQuestion: [],
    currentselectAnswerandQuestion: [],
    currentAllAnswers: [],
    currentCount: 0,
    toView: "",
    loadingHidden: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //options.id=98;
    // options.questionuserid=wx.getStorageSync("userid")
    var scene = decodeURIComponent(options.scene);
    if (scene != 'undefined') {
      that.setData({
        question_id: scene.question_id,
        questionuserid: scene.id
      })
    }
    if (options.id) {
      that.setData({
        question_id: options.id,
        questionuserid: options.questionuserid
      })
    }
  },
  onShow: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
        })
      }
    })
    wx.showLoading({
      title: '加载中...',
    })

    setTimeout(function () {
      wx.hideLoading();
      that.setData({
        loadingHidden: true,
      })
    }, 1600)
    useUserInfo(this);
  },
  hiddenMotai: function () {
    this.setData({
      ishidden: true,
    })

  }
  ,
  selectAnswer: function (e) {
    var that = this;
    var _splce = this.data.allQuestion.splice(1, 1);
    for (var i = 0; i < this.data.currentAllQuestion.length; i++) {
      this.data.currentAllQuestion[i].answer1 = "";
      this.data.currentAllQuestion[i].answer2 = "";
      this.data.currentAllQuestion[i].answer3 = "";
      this.data.currentAllQuestion[i].answer4 = "";
    }
    if (_splce[0]) {
      this.data.currentAllQuestion.push(_splce[0]);
    }
    this.data.currentCount++;
    if (this.data.currentCount == this.data.allQuestionConstantLenght) {
      for (var i = 0; i < this.data.currentAllQuestion.length; i++) {
        this.data.currentAllQuestion[i].answer1 = "";
        this.data.currentAllQuestion[i].answer2 = "";
        this.data.currentAllQuestion[i].answer3 = "";
        this.data.currentAllQuestion[i].answer4 = "";
      }
      this.data.currentAllAnswers.push({
        content: e.target.dataset.content
      })
      this.data.currentselectAnswerandQuestion.push({
        questionId: e.target.dataset.questionid,
        answerId: e.target.id,
      })
      setTimeout(function () {
        that.setData({
          toView: "mark" + that.data.currentCount
        })
      }, 900)
      this.setData({
        currentAllAnswers: this.data.currentAllAnswers,
        currentAllQuestion: this.data.currentAllQuestion,

      })
      sendQuestion(this);
    } else if (this.data.currentCount < this.data.allQuestionConstantLenght) {
      this.data.currentAllAnswers.push({
        content: e.target.dataset.content
      })
      this.data.currentselectAnswerandQuestion.push({
        questionId: e.target.dataset.questionid,
        answerId: e.target.id,
      })
      setTimeout(function () {
        that.setData({
          toView: "mark" + that.data.currentCount
        })
      }, 900)
      this.setData({
        currentAllAnswers: this.data.currentAllAnswers,
        currentAllQuestion: this.data.currentAllQuestion,
      })
    } else {
      return;
    }
  }
})


function getQuestionById(that, _questionuserid) {
  wx.request({
    url: app.globalData.allUrl + "/api/practice_questions.php",//接口差头像跟名称
    data: {
      question_id: that.data.question_id,
      muser_id: _questionuserid,
      puser_id: wx.getStorageSync("userid"),
    },
    header: { 'content-type': "application/x-www-form-urlencoded" },
    method: 'POST',
    success: function (res) {
      console.log(res.data)
      if (res.data == 350) {
        if (that.data.questionuserid == wx.getStorageSync("userid")) {
          setTimeout(function () {
            wx.redirectTo({
              url: '../../pages/myquestions/myquestions?question_id=' + that.data.question_id,
            })
          }, 1000)
        } else {
          setTimeout(function () {
            wx.redirectTo({
              url: '../../pages/result/result?id=2&question_id=' + that.data.question_id,
            })
          }, 1000)
        }
      } else {
        that.data.allQuestion = res.data.data;
        that.data.allQuestionConstantLenght = res.data.data.length;
        that.data.currentAllQuestion.push(res.data.data[0])
        that.setData({
          ishidden: false,
          currentAllQuestion: that.data.currentAllQuestion,
          questionNums: res.data.data.length,
          questionuserInfo: res.data.info[0]
        })
      }
    }
  })
}


function sendQuestion(that) {
  wx.request({
    url: app.globalData.allUrl + "/api/practice_result.php",//穿送答案到后台
    data: {
      question_id: that.data.question_id,
      correct: that.data.currentselectAnswerandQuestion,
      muser_id: that.data.questionuserid,//出题人id
      puser_id: wx.getStorageSync("userid"),//做题人id
    },
    header: { 'content-type': "application/json" },
    method: 'POST',
    success: function (res) {
      console.log(res);
      if (res.data.state == 200) {
        console.log(that.data.questionuserInfo)
        wx.redirectTo({
          url: '../../pages/result/result?id=1&question_id=' + that.data.question_id + "&image_url=" + that.data.questionuserInfo.image_url + "&user_name=" + that.data.questionuserInfo.user_name,
        })
      } else if (res.data.state == 400) {
        wx.redirectTo({
          url: '../../pages/result/result?id=2&question_id=' + that.data.question_id,
        })
      }
    }
  })
}


function useUserInfo(that) {
  if (wx.getStorageSync('userid')) {
    that.setData({
      userInfo: wx.getStorageSync('userInfo')
    })
    if (that.data.question_id) {
      getQuestionById(that, that.data.questionuserid)
    }
  } else {
    wx.login({
      success: function (rese) {
        wx.getUserInfo({
          success: function (res) {
            app.globalData.hasRoot = false;
            app.globalData.noRoot = true;
            wx.setStorageSync('userInfo', res.userInfo)//将用户信息储存在本
            app.globalData.userInfo = res.userInfo;
            that.setData({
              userInfo: res.userInfo
            })
            wx.request({
              url: app.globalData.allUrl + "/api/login.php",
              data: {
                code: rese.code,
              },
              header: { 'content-type': "application/x-www-form-urlencoded" },
              method: 'POST',
              success: function (datas) {
                wx.request({
                  url: app.globalData.allUrl + "/api/saveUserInfo.php",
                  data: {
                    user_id: datas.data.openid,
                    user_name: res.userInfo.nickName,
                    image_url: res.userInfo.avatarUrl,
                  },
                  header: { 'content-type': "application/x-www-form-urlencoded" },
                  method: 'POST',
                  success: function (res) {
                    wx.setStorageSync('userid', datas.data.openid)
                    getQuestionById(that, that.data.questionuserid)
                  }, fail: function () {
                  }
                })
              }, fail: function () {
              }
            })
          }, fail: function () {
            wx.showModal({
              title: '提示',
              content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
              success: function (res) {
                if (res.confirm) {
                  wx.openSetting({
                    success: (res) => {
                      if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录
                        wx.getUserInfo({
                          success: function (res) {
                            app.globalData.hasRoot = false;
                            app.globalData.noRoot = true;
                            wx.setStorageSync('userInfo', res.userInfo)//将用户信息储存在本
                            app.globalData.userInfo = res.userInfo;
                            that.setData({
                              userInfo: res.userInfo
                            })
                            wx.request({
                              url: app.globalData.allUrl + "/api/login.php",
                              data: {
                                code: rese.code,
                              },
                              header: { 'content-type': "application/x-www-form-urlencoded" },
                              method: 'POST',
                              success: function (datas) {
                                wx.request({
                                  url: app.globalData.allUrl + "/api/saveUserInfo.php",
                                  data: {
                                    user_id: datas.data.openid,
                                    user_name: res.userInfo.nickName,
                                    image_url: res.userInfo.avatarUrl,
                                  },
                                  header: { 'content-type': "application/x-www-form-urlencoded" },
                                  method: 'POST',
                                  success: function (res) {
                                    wx.setStorageSync('userid', datas.data.openid)
                                    getQuestionById(that, that.data.questionuserid)
                                  }, fail: function () {
                                  }
                                })
                              }, fail: function () {
                              }
                            })
                          }
                        })
                      }
                    }, fail: function (res) {

                    }
                  })

                }
              }
            })
          }
        })
      }
    })
  }

}
